package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;

    // 处理角色查询分页请求 /role/list
    @RequestMapping("/list")
    @RequiredPermission(name="角色查询", expression = "role:list")
    public String list(Model model, QueryObject qo) {
        PageInfo<Role> pageInfo = roleService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "role/list"; // /WEB-INF/views/role/list.ftl
    }


    // 处理删除请求 /role/delete?id=1
    @RequestMapping("/delete")
    @RequiredPermission(name="角色删除", expression = "role:delete")
    public String delete(Long id) {
        if (id != null) {
            roleService.delete(id);
        }
        return "redirect:/role/list"; // localhost/role/list
    }

    @RequestMapping("/input")
    @RequiredPermission(name="角色编辑", expression = "role:saveOrUpdate")
    public String input(Long id, Model model) {

        List<Permission> permissions = permissionService.listAll();
        model.addAttribute("permissions", permissions);

        // 去修改的话, id 有值
        if(id != null) {
            model.addAttribute("role", roleService.get(id));
            // 查询被编辑的角色的所有具有权限
            List<Permission> ownPermissions = permissionService.queryByRoleId(id);
            model.addAttribute("ownPermissions", ownPermissions);
        }
        return "role/input"; // /WEB-INF/views/role/input.ftl
    }
    
    // 处理保存或者修改请求 /role/saveOrUpdate 参数在请求体
    @RequestMapping("/saveOrUpdate")
    @RequiredPermission(name="角色编辑", expression = "role:saveOrUpdate")
    public String saveOrUpdate(Role role, Long[] permissionIds) {
        if (role.getId() == null) {
            roleService.save(role, permissionIds);
        } else {
            roleService.update(role, permissionIds);
        }
        return "redirect:/role/list"; // localhost/role/list
    }

}
